package group.rober.base.interceptor;

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import group.rober.saber.holder.WebHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Pattern;

/**
 * 视图统一转向器处理
 */
public class ViewRedirectorInterceptor implements HandlerInterceptor {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private String name;
    private String viewDirectory="views/";
    private String startUri;
    private Pattern startUriPattern;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getViewDirectory() {
        return viewDirectory;
    }

    public void setViewDirectory(String viewDirectory) {
        this.viewDirectory = viewDirectory;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;    //只有返回true才会继续向下执行，返回false取消当前请求
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String uri = request.getRequestURI();
        if(startUri==null||startUriPattern==null){
            startUri = name;
            startUriPattern = Pattern.compile(startUri+"(\\.+)\\??");
        }
//        System.out.println("uri:"+uri);
//        System.out.println("startUri:"+startUri);
        if(uri.startsWith(startUri)&&modelAndView==null){
            String relativeUri = uri.substring(startUri.length());
            modelAndView = new ModelAndView();
            modelAndView.setViewName(viewDirectory+relativeUri);
            logger.trace("Redirector-Uri:"+modelAndView.getViewName());
            System.out.println("Redirector-Uri:"+modelAndView.getViewName());
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
